/* Filename : mapping.h
 * 
 * Author   : Shang Wentao
 * Email    : wentaoshang@gmail.com
 * Date     : May 11, 2009
 * 
 * This file contains all the functions and global variables 
 * needed for the port mapping operation. It is not part of 
 * the original Passthru NDIS driver. 
 *
 */

#ifndef _MAPPING_H
#define _MAPPING_H

// 
// Some header format definations
//
typedef struct _iphdr
{
	UCHAR ver_len; 
	UCHAR tos;
	USHORT total_len; // total length (including the header)
	USHORT ident;
	USHORT frag_and_flags;
	UCHAR ttl;
	UCHAR protocol;
	USHORT checksum; // 16 bits checksum
	UCHAR saddr[4];  // 32 bits source address
	UCHAR daddr[4];  // 32 bits destination address
} IP_HEADER,*PIP_HEADER;

typedef struct _ip6hdr
{
	UCHAR    ver_pri;
	UCHAR    flowlbl[3];
	USHORT   payload_len; // payload length (without header length)
	UCHAR    nexthdr;
	UCHAR    hoplimit;
	UCHAR    saddr[16];   // 128 bits source address
	UCHAR    daddr[16];   // 128 bits destination address
} IP6_HEADER,*PIP6_HEADER;

typedef struct _tcphdr
{
	USHORT   srcport;   // 16 bits source port
	USHORT   destport;  // 16 bits destination port
	ULONG    seq;
	ULONG    ack;
	UCHAR    len_res;
	UCHAR    flag;
	USHORT   window;
	USHORT   checksum;  // 16 bits checksum
	USHORT   urp;
} TCP_HEADER,*PTCP_HEADER;

typedef struct _udphdr
{
	USHORT   srcport;   // 16 bits source port
	USHORT   destport;  // 16 bits destination port
	USHORT   len;       // 16 bits total length
	USHORT   checksum;  // 16 bits checksum
} UDP_HEADER,*PUDP_HEADER;


// 
// Map list definitions and functions
//

typedef struct _mapnode
{
	struct _mapnode * pNext;
	USHORT            oldport;
	USHORT            newport;
	LARGE_INTEGER     timer;
} MAP_NODE, *PMAP_NODE;

extern  USHORT  Mod;
extern  USHORT  Res;

// Head of map list! Global variable
extern MAP_NODE Head;

// Spin lock for map list structure
extern NDIS_SPIN_LOCK MapListLock;

extern LARGE_INTEGER TimeOut;

extern INT AutoConfig;

VOID init_list( PMAP_NODE head );

UINT get_list_size( PMAP_NODE head );

INT port_in_use( USHORT port, PMAP_NODE head );

VOID list_add( PMAP_NODE node, PMAP_NODE head );

PMAP_NODE add_new_map( USHORT oldp, USHORT newp, PMAP_NODE head );

INT is_time_out( PLARGE_INTEGER t1, PLARGE_INTEGER t2 );

VOID refresh_list( PMAP_NODE head );

VOID free_list( PMAP_NODE head );

// 
// ntohs and htons, they are the same actually
// no byte-order check! They are unsafe!
//
USHORT ntohs( USHORT number );

USHORT htons( USHORT number );

USHORT checksumadjust( USHORT chksum, USHORT oldp, USHORT newp );

USHORT get_out_map_port( USHORT oldp, PMAP_NODE head, USHORT Mod, USHORT Res );

USHORT get_in_map_port( USHORT newp, PMAP_NODE head );

#endif // _MAPPING_H

